<template>
  <div class="mod-config">
    <el-button-group style="margin-bottom: 10px;">
      <el-button type="primary" icon="el-icon-search" @click="searchHandle">查询</el-button>
      <el-button type="primary" icon="el-icon-delete" @click="searchReset">清空</el-button>
      <el-button v-if="userInfo.roleType&&userInfo.roleType.includes(',ROLE_ADMIN,')" icon="el-icon-refresh" type="primary" @click="syncStudent()">同步</el-button>
      <el-button v-if="permissions.admin_student_add &&userInfo.roleType&&(userInfo.roleType.includes(',ARC_MANAGER,') ||userInfo.roleType.includes(',ROLE_ADMIN,'))" icon="el-icon-plus" type="primary" @click="addOrUpdateHandle('','add')">新增</el-button>
      <el-button v-if="permissions.admin_student_del &&userInfo.roleType&&(userInfo.roleType.includes(',ARC_MANAGER,') ||userInfo.roleType.includes(',ROLE_ADMIN,'))" icon="el-icon-plus" type="primary" @click="delBatchHandle">批量删除</el-button>
      <el-button v-if="permissions.admin_student_add &&userInfo.roleType&&(userInfo.roleType.includes(',ARC_MANAGER,') ||userInfo.roleType.includes(',ROLE_ADMIN,'))" icon="el-icon-upload" type="primary" @click="importExcel()">导入Excel</el-button>
      <el-button type="primary" @click="exportHandle" :loading="isExport">导出</el-button>
      <el-button icon="el-icon-printer" type="primary" @click="printStudent()">打印空白表</el-button>
    </el-button-group>

    <el-button-group style="margin-bottom: 10px;">
      <el-link :href="printUrl" target="_blank" type="primary" :disabled="isDisabled">
        <el-button icon="el-icon-printer" type="primary" @click="getALetterToParents()">打印给家长的一封信</el-button>
      </el-link>
      <el-link :href="printUrl" target="_blank" type="primary" :disabled="isDisabled">
        <el-button icon="el-icon-printer" type="primary" @click="getStudentQrCode()">打印学生二维码</el-button>
      </el-link>
    </el-button-group>
      <el-form inline :model="dataForm" v-if="searchFormShow">
        <el-row class="bg-row">
          <el-col :span="24">
            <el-form-item label="学校区域">
              <el-form-item label-width="0">
                <el-select v-model="dataForm.provinceCode" filterable default-first-option clearable @change="getCityOptions">
                  <el-option v-for="item in provinceOptions" :value="item.id" :label="item.regionName" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="0">
                <el-select v-model="dataForm.cityCode" filterable default-first-option clearable @change="getAreaOptions">
                  <el-option v-for="item in cityOptions" :value="item.id" :label="item.regionName" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="0">
                <el-select v-model="dataForm.areaCode" filterable default-first-option clearable>
                  <el-option v-for="item in areaOptions" :value="item.id" :label="item.regionName" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-form-item>
            <el-form-item label="学校类型">
              <el-select v-model="dataForm.schoolType" @change="schoolTypeChangeHandle" clearable>
                <el-option v-for="item in typeOptions" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row class="bg-row">
          <el-col :span="24">
            <el-form-item label="学校班级">
              <el-form-item label-width="0">
                <el-select filterable default-first-option clearable v-model="dataForm.schoolId" @change="getGradeOption">
                  <el-option v-for="item in schoolOptions" :value="item.id" :label="item.schoolName" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="0">
                <el-select filterable default-first-option clearable v-model="dataForm.gradeId" @change="getClassOption">
                  <el-option v-for="item in gradeOptions" :value="item.id" :label="item.gradeName" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="0">
                <el-select filterable default-first-option clearable v-model="dataForm.classId">
                  <el-option v-for="item in classOptions" :value="item.id" :label="item.className" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-form-item>
            <el-form-item label="学生状态">
              <el-select v-model="dataForm.status">
                <el-option v-for="item in statusOptions" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row class="bg-row">
          <el-col :span="24">
            <el-form-item label="学生学年">
                <el-col :span="11">
                  <el-date-picker style="width: 100%;" v-model="dataForm.fromYear" type="year" value-format="yyyy" placeholder="选择年"></el-date-picker>
                </el-col>
                <el-col :span="2" style="text-align: center;">至</el-col>
                <el-col :span="11">
                  <el-date-picker style="width: 100%;" v-model="dataForm.toYear" type="year" value-format="yyyy" placeholder="选择年"></el-date-picker>
                </el-col>
            </el-form-item>
            <el-form-item label="唯一编码">
              <el-input v-model="dataForm.uniqueCode"></el-input>
            </el-form-item>
            <el-form-item label="学生名称">
              <el-input v-model="dataForm.studentName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="dataList" height="calc(100vh - 215px)" border stripe v-loading="dataListLoading" @selection-change="handleSelectionChange" @sort-change="sortChangeHandle">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="uniqueCode" label="唯一编码" width="80"></el-table-column>
        <el-table-column column-key="student_name" prop="studentName" label="学生姓名" width="100" :sortable="'custom'"></el-table-column>
        <el-table-column column-key="birth_day" prop="birthDay" label="出生年月" width="120" :sortable="'custom'"></el-table-column>
        <el-table-column prop="gender" label="性别" width="120">
          <template slot-scope="scope">
            <el-tag effect="dark" v-if="scope.row.gender == 0">男</el-tag>
            <el-tag effect="dark" type="success" v-if="scope.row.gender == 1">女</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="telPhone" label="手机号" width="120"></el-table-column>
        <el-table-column prop="fullName" label="班级名称" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag effect="dark" v-if="scope.row.status == 0">正常</el-tag>
            <el-tag effect="dark" type="warning" v-if="scope.row.status == 1">转学</el-tag>
            <el-tag effect="dark" type="danger" v-if="scope.row.status == 2">休学</el-tag>
            <el-tag effect="dark" type="danger" v-if="scope.row.status == 3">停用</el-tag>
            <el-tag effect="dark" type="danger" v-if="scope.row.status == 9">历史</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="280">
          <template slot-scope="scope">
            <el-button type="text" @click="addOrUpdateHandle(scope.row.id,'check')">详情</el-button>
            <el-button v-if="userInfo.roleType&&(userInfo.roleType.includes(',ARC_MANAGER,') ||userInfo.roleType.includes(',ROLE_ADMIN,'))" type="text" @click="studentStopHandle(scope.row.id)">停用</el-button>
            <!-- <el-button v-if="userInfo.roleType&&(userInfo.roleType.includes(',ARC_MANAGER,') ||userInfo.roleType.includes(',ROLE_ADMIN,'))" type="text" @click="transferHandle(scope.row.id)">转学</el-button>
            <el-button v-if="userInfo.roleType&&(userInfo.roleType.includes(',ARC_MANAGER,') ||userInfo.roleType.includes(',ROLE_ADMIN,'))" type="text" @click="suspensionHandle(scope.row.id)">休学</el-button> -->
            <el-button v-if="userInfo.roleType&&(userInfo.roleType.includes(',ARC_MANAGER,') ||userInfo.roleType.includes(',ROLE_ADMIN,'))" type="text" @click="putOnRecordHandle(scope.row)">检查</el-button>
            <el-button v-if="permissions.admin_student_edit &&userInfo.roleType&&(userInfo.roleType.includes(',ARC_MANAGER,') ||userInfo.roleType.includes(',ROLE_ADMIN,'))" type="text" @click="addOrUpdateHandle(scope.row.id,'edit')">编辑</el-button>
            <el-button v-if="permissions.admin_student_del &&userInfo.roleType&&(userInfo.roleType.includes(',ARC_MANAGER,') ||userInfo.roleType.includes(',ROLE_ADMIN,'))" type="text" @click="deleteHandle(scope.row)">删除</el-button>
            <el-link :href="printUrl" :underline="false" target="_blank" type="primary" :disabled="isDisabled">
              <el-button icon="el-icon-printer" type="text" @click="ontALetterToParentsPrint(scope.row)">家长一封信</el-button>
            </el-link>
            <el-link :href="printUrl" :underline="false" target="_blank" type="primary" :disabled="isDisabled">
              <el-button icon="el-icon-printer" type="text" @click="ontStudentQrCode(scope.row)">二维码</el-button>
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="avue-crud__pagination" style="margin-bottom: 25px;">
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100, 200]"
          :page-size="pageSize"
          :total="totalPage"
          background
          layout="total, sizes, prev, pager, next">
        </el-pagination>
      </div>

      <!-- 弹窗, 新增 / 修改 -->
      <table-form v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></table-form>
      <!-- 弹窗, 导入excel -->
      <excel-import v-if="excelVisible" ref="excelDialog" :fromYear="dataForm.fromYear" :toYear="dataForm.toYear"></excel-import>
      <check-data v-if="checkVisible" ref="checkDialog"></check-data>
  </div>
</template>

<script>
  let params = "";
  import { mapGetters } from 'vuex'
  import { filterParams } from '@/util/tools'
  import { remote } from '@/api/admin/dict'
  import { getListByParentId } from '@/api/admin/region'
	import { getCurrentYear } from '@/api/pvm/filingRate'
  import { fetchList, delObj,printStudent,printOneStudent,syncStudent, studentTransfer, studentSuspension, delBatchObj, studentStop } from '@/api/pvm/student'
  import { getSchoolList , getClassOptions, getSchoolListBySchoolType } from '@/api/pvm/school'
  import { getGradeBySchoolId } from '@/api/pvm/grade'
  import { getStudentCheckDetailExport } from '@/api/pvm/filingRate'

  import TableForm from './TableForm'
  import ExcelImport from './ExcelImport'
  import PutRecord from '@/views/pvm/arcoptometry/form'
  import CheckData from './CheckData'

  export default {
    name: 'pvmstudent',
    data() {
      return {
        printUrl: "",
        isDisabled: true,
        searchFormShow: true,
        isExport: false,
        dataList: [],
        dataListLoading: false,
        column: "",
        asc: true,
        pageIndex: 1,
        pageSize: 100,
        totalPage: 0,
        dataForm: {},
        ids: [],
        provinceOptions: [],
        cityOptions: [],
        areaOptions: [],
        typeOptions: [],
        schoolOptions: [],
        gradeOptions: [],
        classOptions: [],
        statusOptions: [],
        addOrUpdateVisible: false,
        excelVisible: false,
        checkVisible: false
      }
    },
    components: {
      TableForm,
      ExcelImport,
      CheckData
    },
    computed: {
      ...mapGetters(['permissions','userInfo', "bizData"])
    },
    created() {
      this.getProvinceOptions()
      this.getSchoolTypeList()
      this.getSchoolOptions()
      this.getStudentStatus()
      this.searchHandle()
      this.getCurrentYear()
    },
    methods: {
      // 查询数据
      searchHandle(){
        //console.log(this.dataForm.fromYear)
        this.pageIndex = 1
        this.getDataList()
      },
      // 清空查询表单
      searchReset(){
        for(let key in this.dataForm){
          this.dataForm[key] = ''
        }
      },
      // 获取当前学年
			getCurrentYear(){
			  getCurrentYear().then(response => {
          if(response.data.code == '0'){
            let resultData = response.data.data
            let yearArr = resultData.split(',')
            this.$set(this.dataForm,'fromYear',yearArr[0])
            this.$set(this.dataForm,'toYear',yearArr[1])
          }else{
            this.$message.error(response.data.msg)
          }
			  })
			},
      // 获取数据列表
      getDataList(){
        let params1 = {current: this.pageIndex,size: this.pageSize,column: this.column,asc:this.asc}
        let params2 = filterParams(this.dataForm)
        this.dataListLoading = true
        fetchList(Object.assign(params1,params2)).then(response => {
          if(response.data.code == '0'){
            this.dataList = response.data.data.records
            this.totalPage = response.data.data.total
          }else{
            this.$message.error(response.data.msg)
          }
          this.dataListLoading = false
        })
      },
      // 每页条数改变
      sizeChangeHandle(val){
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页改变
      currentChangeHandle(val){
        this.pageIndex = val
        this.getDataList()
      },
      // 打开弹窗 新增 / 修改 / 详情
      addOrUpdateHandle(id,type){
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id,type)
        })
      },
      // 排序
      sortChangeHandle(column){
        let asc = ''
        if(column.order != null){
          if(column.order == 'ascending'){
            asc = true
          }else if(column.order == 'descending'){
            asc = false
          }
        }
        this.column = column.column.columnKey || column.prop
        this.asc=asc
        this.searchHandle()
      },
      // 删除教师
      deleteHandle(row){
        this.$confirm('此操作将永久删除该学生(学生名为:' + row.studentName + '), 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delObj(row.id)
        }).then(response => {
          if(response.data.code == '0'){
            this.$message.success('删除成功')
            this.getDataList()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 学生停用
      studentStopHandle(id){
        this.$confirm('此操作将停用该学生?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return studentStop(id)
        }).then(response => {
          if(response.data.code == '0'){
            this.$message.success('停用成功')
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 获取省级地址列表
      getProvinceOptions(){
        var parentId = '86';
        getListByParentId(parentId).then(response => {
          if(response.data.code == '0'){
            this.provinceOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        }).catch(() => {
          alert("省级地址出错了，请联系管理员")
        });
      },
      // 获取市级地址列表
      getCityOptions(val){
        this.cityOptions = []
        this.areaOptions = []
        this.$set(this.dataForm,'cityCode','')
        this.$set(this.dataForm,'areaCode','')
        if(val){
          getListByParentId(val).then(response => {
            if(response.data.code == '0'){
              this.cityOptions = response.data.data
            }else{
              this.$message.error(response.data.msg)
            }
          }).catch(() => {
            alert("市级地址出错了，请联系管理员")
          });
        }
      },
      // 获取区/县级地址列表
      getAreaOptions(val){
        this.areaOptions = []
        this.$set(this.dataForm,'areaCode','')
        if(val){
          getListByParentId(val).then(response => {
            if(response.data.code == '0'){
              this.areaOptions = response.data.data
            }else{
              this.$message.error(response.data.msg)
            }
          }).catch(() => {
            alert("市级地址出错了，请联系管理员")
          });
        }
      },
      // 获取学校类型列表
      getSchoolTypeList(){
        remote('school_type').then(response => {
          let responseData = response.data.data
          let list = []
          responseData.forEach(item => {
            list.push({label: item.label, value: item.value*1})
          })
          this.typeOptions = list
        })
      },
      schoolTypeChangeHandle(val){
        this.schoolOptions = []
        this.gradeOptions = []
        this.classOptions = []
        this.$set(this.dataForm,'schoolId','')
        this.$set(this.dataForm,'gradeId','')
        this.$set(this.dataForm,'classId','')
        this.getSchoolOptions()
      },
      // 获取学校列表
      getSchoolOptions(data){
        let schoolType = ''
        if(this.dataForm.schoolType === 0){
          schoolType = 0
        }else{
          schoolType = this.dataForm.schoolType || ''
        }
        getSchoolListBySchoolType(schoolType).then(response => {
          if(response.data.code == '0'){
            this.schoolOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      syncStudent(){
        let form = {...this.dataForm}
        let params2 = filterParams(form)
        syncStudent(params2).then(response=>{
          if(response.data.code == '0'){
            this.$message.success('同步成功')
            this.getDataList()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      handleSelectionChange(val){
        this.ids = val
      },
      // 批量删除学生
      delBatchHandle(){
        let that = this
        let ids = this.ids.map(item => {
          return item.id
        })
        this.$confirm('该批学生将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delBatchObj(ids)
        }).then(response => {
          if(response.data.code == '0'){
            this.$message.success('删除成功')
            this.getDataList()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 获取年级列表
      getGradeOption(schoolId){
        this.gradeOptions = []
        this.classOptions = []
        this.$set(this.dataForm,'gradeId','')
        this.$set(this.dataForm,'classId','')
        getGradeBySchoolId(schoolId).then(response => {
          if(response.data.code == '0'){
            this.gradeOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 获取班级列表
      getClassOption(gradeId){
        this.classOptions = []
        this.$set(this.dataForm,'classId','')
        getClassOptions(this.dataForm.schoolId,gradeId).then(response => {
          if(response.data.code == '0'){
            this.classOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 获取学生状态列表
      getStudentStatus(){
        remote('student_status').then(response => {
          if(response.data.code == '0'){
            let responseData = response.data.data
            let list = []
            responseData.forEach(item => {
              list.push({label: item.label, value: item.value*1})
            })
            this.statusOptions = list
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      //  转换类型格式
      statusFormat(val){
        let obj = {}
        obj = this.typeOptions.find(item => {
          if(item.value === val){
            return item
          }
        })
        if(obj && obj.label){
          return obj.label
        }
      },
      importExcel(){
        if(this.dataForm.fromYear && this.dataForm.toYear){
          this.excelVisible = true
          this.$nextTick(() => {
            this.$refs.excelDialog.init()
          })
        }else{
          this.$message.warning('请选择学年')
        }
      },
      printStudent(){
        printStudent(Object.assign(this.dataForm)).then(response => {

            var blob = new Blob([response.data], {
                type: 'application/pdf;chartset=UTF-8'
            });
            var reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onload = function(e) {
                var a = document.createElement('a');
                a.download = "学生空白表.pdf";
                a.href = URL.createObjectURL(blob);
                a.click();
            }
        })
      },
      // 转学
      transferHandle(id){
        studentTransfer(id).then(response => {
          if(response.data.code == '0'){
            this.$message.success('转学成功')
            this.searchHandle()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 休学
      suspensionHandle(id){
        studentSuspension(id).then(response => {
          if(response.data.code == '0'){
            this.$message.success('休学成功')
            this.searchHandle()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 检查
      putOnRecordHandle(row) {
        this.checkVisible = true
        this.$nextTick(() => {
          this.$refs.checkDialog.init(row)
        })
      },
      getALetterToParents() {
        if(!this.dataForm.fromYear){
          this.$message.warning('请输入学年')
          return
        }
        if(!this.dataForm.toYear){
          this.$message.warning('请输入学年')
          return
        }
        this.isDisabled = false
        params = "/a_letter_to_parents.cpt"
        let data = filterParams(this.dataForm)
        let parameter = ""
        for (let key in data) {
          parameter += "&" + key + "=" + this.dataForm[key]
        }
        this.printUrl = this.bizData.printUrl + params + parameter
      },
      getStudentQrCode() {
        if(!this.dataForm.fromYear){
          this.$message.warning('请输入学年')
          return
        }
        if(!this.dataForm.toYear){
          this.$message.warning('请输入学年')
          return
        }
        this.isDisabled = false
        params = "/qr_code.cpt"
        let data = filterParams(this.dataForm)
        let parameter = ""
        for (let key in data) {
          parameter += "&" + key + "=" + this.dataForm[key]
        }
        this.printUrl = this.bizData.printUrl + params + parameter
      },
      ontALetterToParentsPrint(row) {
        if(!this.dataForm.fromYear){
          this.$message.warning('请输入学年')
          return
        }
        if(!this.dataForm.toYear){
          this.$message.warning('请输入学年')
          return
        }
        this.isDisabled = false
        params = "/a_letter_to_parents.cpt"
        let data = filterParams(this.dataForm)
        let parameter = "&studentName="+row.studentName+"&studentId="+row.id
        for (let key in data) {
          parameter += "&" + key + "=" + this.dataForm[key]
        }
        this.printUrl = this.bizData.printUrl + params + parameter
      },
      ontStudentQrCode(row) {
        if(!this.dataForm.fromYear){
          this.$message.warning('请输入学年')
          return
        }
        if(!this.dataForm.toYear){
          this.$message.warning('请输入学年')
          return
        }
        this.isDisabled = false
        params = "/qr_code.cpt"
        let data = filterParams(this.dataForm)
        let parameter = "&studentId="+row.id
        for (let key in data) {
          parameter += "&" + key + "=" + this.dataForm[key]
        }
        this.printUrl = this.bizData.printUrl + params + parameter
      },
      // 导出
      exportHandle() {
        this.isExport = true
        getStudentCheckDetailExport(this.dataForm).then(response => {
            this.isExport = false
            var blob = new Blob([response.data], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            });
            var reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onload = function(e) {
              var a = document.createElement('a');
              a.download = "建档学生信息表.xlsx";
              a.href = URL.createObjectURL(blob);
              a.click();
            }
            this.$message.success("导出成功")
        }).catch(() => {
          this.isExport = false
        })
      },
    }
  }
</script>
